<template>
  <div>
    <!-- 表格显示 -->
    <el-table :data="storageEntries" style="width: 100%">
      <el-table-column prop="entryDate" label="入库日期" :formatter="formatDate"></el-table-column>
      <el-table-column prop="licensePlate" label="车牌号"></el-table-column>
      <el-table-column prop="itemCount" label="物品数量"></el-table-column>
      <el-table-column prop="itemWeightTon" label="物品重量（吨）"></el-table-column>
      <el-table-column prop="portId" label="港口名称" :formatter="formatPortName"></el-table-column>
      <el-table-column prop="companyId" label="公司名称" :formatter="formatCompanyName"></el-table-column>
      <el-table-column label="操作">
        <template v-slot="scope">
          <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 新增进口订单按钮 -->
    <el-button type="primary" @click="showAddDialog">新增进口订单</el-button>

    <!-- 新增/编辑对话框 -->
    <el-dialog v-model="dialogVisible" title="进口订单信息">
      <el-form :model="entryForm">
        <el-form-item label="入库日期">
          <el-date-picker v-model="entryForm.entryDate" type="date" placeholder="选择日期"></el-date-picker>
        </el-form-item>
        <el-form-item label="车牌号">
          <el-input v-model="entryForm.licensePlate"></el-input>
        </el-form-item>
        <el-form-item label="物品数量">
          <el-input v-model="entryForm.itemCount" type="number"></el-input>
        </el-form-item>
        <el-form-item label="物品重量（吨）">
          <el-input v-model="entryForm.itemWeightTon" type="number"></el-input>
        </el-form-item>
        <el-form-item label="港口">
          <el-select v-model="entryForm.portId" placeholder="选择港口">
            <el-option v-for="port in ports" :key="port.portId" :label="port.portName" :value="port.portId"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="公司">
          <el-select v-model="entryForm.companyId" placeholder="选择公司">
            <el-option v-for="company in companies" :key="company.companyId" :label="company.companyName" :value="company.companyId"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">{{ isEditing ? '保存' : '添加' }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  data() {
    return {
      storageEntries: [], // 进口订单列表数据
      ports: [], // 港口数据
      companies: [], // 公司数据
      dialogVisible: false, // 对话框显示状态
      isEditing: false, // 当前操作是否为编辑
      entryForm: {
        entryId: null,
        entryDate: '',
        licensePlate: '',
        itemCount: null,
        itemWeightTon: null,
        portId: null,
        companyId: null
      }
    };
  },
  mounted() {
    this.fetchStorageEntries();
    this.fetchPortsAndCompanies();
  },
  methods: {
    // 获取进口订单列表
    fetchStorageEntries() {
      axios.get('http://localhost:8080/storageentry/list')
          .then(response => {
            if (response.data.code === 200) {
              this.storageEntries = response.data.data;
            } else {
              this.$message.error('获取进口订单列表失败');
            }
          })
          .catch(error => {
            console.error(error);
            this.$message.error('获取进口订单列表出错');
          });
    },
    // 获取港口和公司数据
    fetchPortsAndCompanies() {
      // 获取港口数据
      axios.get('http://localhost:8080/port/list')
          .then(response => {
            if (response.data.code === 200) {
              this.ports = response.data.data;
            } else {
              this.$message.error('获取港口列表失败');
            }
          })
          .catch(error => {
            console.error(error);
            this.$message.error('获取港口列表出错');
          });

      // 获取公司数据
      axios.get('http://localhost:8080/company/list')
          .then(response => {
            if (response.data.code === 200) {
              this.companies = response.data.data;
            } else {
              this.$message.error('获取公司列表失败');
            }
          })
          .catch(error => {
            console.error(error);
            this.$message.error('获取公司列表出错');
          });
    },
    // 格式化日期
    formatDate(row, column, cellValue) {
      return cellValue ? new Date(cellValue).toLocaleDateString() : '';
    },
    // 格式化港口名称
    formatPortName(row) {
      const port = this.ports.find(p => p.portId === row.portId);
      return port ? port.portName : '';
    },
    // 格式化公司名称
    formatCompanyName(row) {
      const company = this.companies.find(c => c.companyId === row.companyId);
      return company ? company.companyName : '';
    },
    // 编辑进口订单信息
    handleEdit(entry) {
      this.isEditing = true;
      this.dialogVisible = true;
      this.entryForm = { ...entry, entryDate: new Date(entry.entryDate) };
    },
    // 显示新增进口订单对话框
    showAddDialog() {
      this.isEditing = false;
      this.dialogVisible = true;
      this.resetForm();
    },
    // 删除进口订单
    handleDelete(entry) {
      axios.delete(`http://localhost:8080/storageentry/delete/${entry.entryId}`)
          .then(response => {
            if (response.data.code === 200) {
              this.$message.success('删除成功');
              this.fetchStorageEntries(); // 重新获取进口订单列表
            } else {
              this.$message.error('删除失败');
            }
          })
          .catch(error => {
            console.error(error);
            this.$message.error('删除出错');
          });
    },
    // 提交表单
    handleSubmit() {
      // 确保日期格式为字符串，或者是后端可以识别的格式
      if (this.entryForm.entryDate) {
        this.entryForm.entryDate = this.entryForm.entryDate.toISOString().slice(0, 10);
      }

      console.log("Submitting form data:", this.entryForm);

      if (this.isEditing) {
        axios.put('http://localhost:8080/storageentry/update', this.entryForm)
            .then(response => {
              console.log("Update response:", response);
              if (response.data.code === 200) {
                this.$message.success('更新成功');
                this.fetchStorageEntries(); // 重新获取进口订单列表
                this.dialogVisible = false;
                this.resetForm();
              } else {
                this.$message.error('更新失败');
              }
            })
            .catch(error => {
              console.error(error);
              this.$message.error('更新出错');
            });
      } else {
        axios.post('http://localhost:8080/storageentry/add', this.entryForm)
            .then(response => {
              console.log("Add response:", response);
              if (response.data.code === 200) {
                this.$message.success('新增成功');
                this.fetchStorageEntries(); // 重新获取进口订单列表
                this.dialogVisible = false;
                this.resetForm();
              } else {
                this.$message.error('新增失败');
              }
            })
            .catch(error => {
              console.error(error);
              this.$message.error('新增出错');
            });
      }
    },
    // 重置表单
    resetForm() {
      this.entryForm = {
        entryId: null,
        entryDate: '',
        licensePlate: '',
        itemCount: null,
        itemWeightTon: null,
        portId: null,
        companyId: null
      };
    }
  }
};
</script>

<style scoped>
/* 可选：自定义样式 */
.el-dialog {
  /* 确保对话框在最前 */
  z-index: 9999 !important;
}
</style>
